﻿using System.Collections;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;

public partial class RequestServerController
{
    static RequestServerController _instance;
    public static RequestServerController instance
    {
        get
        {
            if (_instance == null)
                _instance = new RequestServerController();

            return _instance;
        }
    }

    Dictionary<long, UserInfo> userInfoDict = new Dictionary<long, UserInfo>();

    public void RequestUserInfo( long uId,Action<UserInfo> onGetUserInfo,bool onlyIcon = true)
    {
        if (userInfoDict.ContainsKey(uId))
        {
            onGetUserInfo?.Invoke(userInfoDict[uId]);
        }
        else
        {
            RequestUserInfo(new long[1] { uId }, (uis) =>
            {
                onGetUserInfo?.Invoke(uis[0]);
            },onlyIcon);
        }
    }
    public void RequestUserInfo(long[] uIds, Action<UserInfo[]> callback, bool onlyIcon = true)
    {
        Request_FetchUserInfos request = new Request_FetchUserInfos();
        request.fetchUserInfosReqData.userIds = uIds;
        request.fetchUserInfosReqData.onlyIcon = onlyIcon;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_FetchUserInfos onResponse:" + response.responseData.code);

            FetchUserInfoResponseData fetchUserInfos = response.responseData as FetchUserInfoResponseData;

            if (response.responseData.code == 0)
            {
                callback?.Invoke(fetchUserInfos.userInfos);

                foreach(var userinfo in fetchUserInfos.userInfos)
                {
                    userInfoDict[userinfo.userId] = userinfo;
                }
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke(null);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_FetchUserInfos onTimeOut ");
            callback?.Invoke(null);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }

    Dictionary<long, MiniUserInfo> miniUserInfoDict = new Dictionary<long, MiniUserInfo>();
    public void RequestMiniUserInfo(long[] uIds, Action<MiniUserInfo[]> callback)
    {
        List<long> toReq = new List<long>(uIds);

        GameDebug.Log($"RequestMiniUserInfo:{uIds}");

        foreach(var uId in uIds)
        {
            if (this.miniUserInfoDict.ContainsKey(uId))
            {
                toReq.Remove(uId);
            }
        }
        if(toReq.Count <= 0)
        {
            MiniUserInfo[] ret = new MiniUserInfo[uIds.Length];
            for (int i = 0; i < uIds.Length; i++)
            {
                long uid = uIds[i];
                ret[i] = miniUserInfoDict[uid];
            }
            callback?.Invoke(ret);
            return;
        }

        GameDebug.Log($"RequestMiniUserInfo remote req:{toReq.GetListStr()}");

        Request_FetchMiniUserInfos request = new Request_FetchMiniUserInfos();
        request.fetchUserInfosReqData.userIds = toReq.ToArray();

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("RequestMiniUserInfo onResponse:" + response.responseData.code);

            FetchMiniUserInfoResponseData fetchUserInfos = response.responseData as FetchMiniUserInfoResponseData;

            if (response.responseData.code == 0)
            {
                //callback?.Invoke(fetchUserInfos.miniUserInfos);

                GameDebug.Log("MiniUserInfo response:" + fetchUserInfos.miniUserInfos.GetArrStr());

                foreach (var userinfo in fetchUserInfos.miniUserInfos)
                {
                    miniUserInfoDict[userinfo.userId] = userinfo;
                }

                MiniUserInfo[] ret = new MiniUserInfo[uIds.Length];
                for(int i = 0; i < uIds.Length; i++)
                {
                    long uid = uIds[i];
                    if (miniUserInfoDict.ContainsKey(uid))
                        ret[i] = miniUserInfoDict[uid];
                    else
                        GameDebug.LogError($"cant find userinfo:{uid}");
                }
              
                callback?.Invoke(ret);
            }
            else
            {
                MGame.instance.ShowNoticePanel($"网络出错，请重试");
                callback?.Invoke(null);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_FetchUserInfos onTimeOut ");
            callback?.Invoke(null);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }

    ExplorePanelData exploreData;
    public void ReqExploreData(int num,Action<ExplorePanelData> callback)
    {
        if (exploreData != null)
        {
            callback?.Invoke(exploreData);
            return;
        }
        Request_FetchCandidates request = new Request_FetchCandidates();
        request.fetchCandidatesReqData.num = num;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_FetchCandidates onResponse:" + response.responseData.code);

            FetchCandidatesResponseData fetchCandidates = response.responseData as FetchCandidatesResponseData;

            if (response.responseData.code == 0)
            {
                ExplorePanelData data = new ExplorePanelData();
                data.candidates = fetchCandidates.candidates;

                callback?.Invoke(data);
                exploreData = data;
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke(null);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_FetchCandidates onTimeOut ");
            callback?.Invoke(null);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }


    public void ReqBaseInfo(UserBaseInfoData userBaseInfoData, Action<int> callback)
    {
        Request_UploadBaseInfo request = new Request_UploadBaseInfo();
        request.baseInfoReqData.userBaseInfoData = userBaseInfoData;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_UploadBaseInfo onResponse:"+response.responseData.code);

            var responseData = response.responseData as ImageUrlResponseData;
            if (response.responseData.code == 0 && responseData != null)
            {
                var userInfo = MGame.instance.MUser.userInfo;
                userInfo.gender = userBaseInfoData.gender;
                userInfo.birthYear = userBaseInfoData.birthYear;
                userInfo.eduation = userBaseInfoData.edu;
                userInfo.locationCity = userBaseInfoData.locationCity;
                userInfo.locationProvince = userBaseInfoData.locationProvince;
                userInfo.icon = responseData.url;

                MGame.instance.MUser.UpdateLocalData();

                callback?.Invoke(0);
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke(-1);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_UploadBaseInfo onTimeOut ");
            callback?.Invoke(-1);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }

    public void ReqDetailInfo(UserDetailInfoData userDetailInfoData, Action<int> callback)
    {
        Request_UploadDetailInfo request = new Request_UploadDetailInfo();
        request.detailInfoReqData.userDetailInfoData = userDetailInfoData;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_UploadDetailInfo onResponse:" + response.responseData.code);

            if (response.responseData.code == 0)
            {
                var userInfo = MGame.instance.MUser.userInfo;
                userInfo.height = userDetailInfoData.height;
                userInfo.weight = userDetailInfoData.weight;
                userInfo.maritalStatus = userDetailInfoData.maritalStatus;
                userInfo.hometownCity = userDetailInfoData.hometownCity;
                userInfo.job = userDetailInfoData.job;

                MGame.instance.MUser.UpdateLocalData();

                callback?.Invoke(0);
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke(-1);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_UploadDetailInfo onTimeOut ");
            callback?.Invoke(-1);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }

    public void ReqUpdateIntroduction(int type, string content,Action<int> callback)
    {
        Request_UpdateIntroduction request = new Request_UpdateIntroduction();
        request.editIntroductionReqData.type = type;
        request.editIntroductionReqData.content = content;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_UpdateIntroduction onResponse:" + response.responseData.code);

            if (response.responseData.code == 0)
            {
                var userInfo = MGame.instance.MUser.userInfo;
                if(type == IntroductioType.aboutMe)
                    userInfo.aboutMe = content;
                else if (type == IntroductioType.familyBackground)
                    userInfo.familyBackground = content;
                else if (type == IntroductioType.interest)
                    userInfo.interest = content;
                else if (type == IntroductioType.loveView)
                    userInfo.loveView = content;
                else if (type == IntroductioType.idealCompanion)
                    userInfo.idealCompanion = content;

                MGame.instance.MUser.UpdateLocalData();

                callback?.Invoke(0);
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke(-1);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_UpdateIntroduction onTimeOut ");
            callback?.Invoke(-1);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }

    public void ReqUploadPhotos(int texId,Tex tex, Action<string> callback)
    {
        Request_UploadPhoto request = new Request_UploadPhoto();
        request.uploadPhotosRequestData.tex = tex;
        request.uploadPhotosRequestData.texId = texId;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_UploadPhoto onResponse:" + response.responseData.code);

            var responseData = response.responseData as ImageUrlResponseData;

            if (response.responseData.code == 0 && responseData != null)
            {
                var userInfo = MGame.instance.MUser.userInfo;
                if (texId == TexId.icon) userInfo.icon = responseData.url;
                if (texId == TexId.tex1) userInfo.tex1 = responseData.url;
                if (texId == TexId.tex2) userInfo.tex2 = responseData.url;
                if (texId == TexId.tex3) userInfo.tex3 = responseData.url;
                if (texId == TexId.tex4) userInfo.tex4 = responseData.url;
                if (texId == TexId.tex5) userInfo.tex5 = responseData.url;
                if (texId == TexId.tex6) userInfo.tex6 = responseData.url;

                callback?.Invoke(responseData.url);

                MGame.instance.MUser.UpdateLocalData();
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke("");
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_UploadPhoto onTimeOut ");
            callback?.Invoke("");
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }

    public void ReqApply(long targetUserId, string message, Action<Apply> callback)
    {
        Request_Apply request = new Request_Apply();
        request.applyReqData.targetUserId = targetUserId;
        request.applyReqData.message = message;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_Apply onResponse:" + response.responseData.code);

            if (response.responseData.code == 0)
            {
                ApplyResponseData applyResponseData = response.responseData as ApplyResponseData;
               
                callback?.Invoke(applyResponseData.apply);

                MGame.instance.MUser.AddApply(applyResponseData.apply);
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                callback?.Invoke(null);
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_Apply onTimeOut ");
            callback?.Invoke(null);
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }


    public void ReqPayment(PaymentValidateData paymentValidateData,Action<string> onFail, Action<PaymentValidateResponseData> callback)
    {
        Request_PaymentValidate request = new Request_PaymentValidate();
        request.validateData = paymentValidateData;

        request.onResponse = delegate (ResponseBase response)
        {
            GameDebug.Log("Request_PaymentValidate onResponse:" + response.responseData.code);

            if (response.responseData.code == 0)
            {
                PaymentValidateResponseData payResponseData = response.responseData as PaymentValidateResponseData;

                callback?.Invoke(payResponseData);

                //MGame.instance.MUser.AddApply(applyResponseData.apply);
            }
            else
            {
                MGame.instance.ShowNoticePanel("网络出错，请重试");
                onFail?.Invoke("payment fail");
            }
        };
        request.onTimeOut = delegate (RequestBase req)
        {
            GameDebug.Log("Request_PaymentValidate onTimeOut ");
            onFail?.Invoke("payment timeout");
        };

        request.clientSocket = MGame.instance.clientSocket;
        request.timeOutSeconds = 12;
        request.Send();
    }
}



